﻿using System;
using System.Runtime.Caching;

namespace PageAdmin.Utils.ORM
{
    /// <summary>
    /// 数据库专用缓存类，只提供Remove方法用于清除数据表的缓存。
    /// </summary>
    public class DbCacheHelper
    {
        /// <summary>
        /// 获取系统提供的默认缓存
        /// </summary>
        private static ObjectCache DefaultCache
        {
            get
            {
                return MemoryCache.Default;
            }
        }

        /// <summary>
        /// 获取缓存
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="key"></param>
        /// <returns></returns>
        internal static T Get<T>(string key)
        {
            if (DefaultCache.Contains(key))
            {
                return (T)DefaultCache[key];
            }
            else
            {
                return default(T);
            }
        }

        /// <summary>
        /// 添加一个缓存
        /// </summary>
        /// <param name="key"></param>
        /// <param name="data"></param>
        /// <param name="cacheMinutes"></param>
        internal static void Add(string key, object data, double cacheMinutes)
        {
            if (cacheMinutes == 0)
            {
                return;
            }
            if (data == null) return;
            if (!Contains(key))
            {
                var policy = new CacheItemPolicy();//缓存策略
                policy.AbsoluteExpiration = DateTime.Now.AddMinutes(cacheMinutes);
                DefaultCache.Add(new CacheItem(key, data), policy);
            }
        }

        internal static bool Contains(string key)
        {
            return DefaultCache.Contains(key);
        }

        /// <summary>
        /// 清空动态列表缓存
        /// </summary>
        /// <param name="key">键名</param>
        public static void Remove(string table)
        {
            string key = table + "_dynamic_cache";
            if (Contains(key))
            {
                DefaultCache.Remove(key);
            }
        }
        /// <summary>
        /// 清空实体缓存
        /// </summary>
        /// <typeparam name="T"></typeparam>
        public static void Remove<T>() where T : class, new()
        {
            string key = AttributeHelper.GetTableName(typeof(T)) + "_model_cache";
            if (Contains(key))
            {
                DefaultCache.Remove(key);
            }
        }

    }
}